package common;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class UserListHolder implements Serializable {

	public static final int DEFAULT_PAGE_SIZE = 10;
	private List source;
	private Date refreshDate;
	private int pageSize = DEFAULT_PAGE_SIZE;
	private int page = 0;

	private boolean newPageSet;

	public List getSource() {
		return source;
	}

	public void setSource(List source) {
		this.source = source;
	}

	public Date getRefreshDate() {
		return refreshDate;
	}

	public UserListHolder() {
		this(new ArrayList(0));
	}

	public UserListHolder(List source) {
		// TODO Auto-generated constructor stub
		this.source = source;
		this.refreshDate = new Date();
	}

	public void setPageSize(int pageSize) {
		if (pageSize != this.pageSize) {
			this.pageSize = pageSize;
			if (!this.newPageSet) {
				this.page = 0;
			}
		}
	}

	public int getPageSize() {
		return pageSize;
	}

	public int getPage() {
		this.newPageSet = false;
		if (this.page >= getPageCount()) {
			this.page = getPageCount() - 1;
		}
		return this.page;
	}

	public void setPage(int page) {
		this.page = page;
		this.newPageSet = true;
	}

	public int getPageCount() {
		float nrOfPages = (float) getSource().size() / getPageSize();
		return (int)((nrOfPages > (int)nrOfPages || nrOfPages == 0.0)?nrOfPages+1:nrOfPages);
	}
	
	public boolean isFirstPage(){
		return getPage()==0;
	}
	
	public boolean isLastPage(){
		return getPage() == getPageCount() - 1;
	}
	
	public void previousPage(){
		if (!isFirstPage()){
			this.page--;
		}
	}
	
	public void nextPage(){
		if (!isLastPage()){
			this.page++;
		}
	}
	
	public int getNrOfElements(){
		return getSource().size();
	}
	
	public int getFirstElementOnPage(){
		return (getPageSize()*getPage());
	}
	
	public int getLastElementOnPage(){
		int endIndex = getPageSize()*(getPage()+1);
		return (endIndex > getSource().size()?getSource().size():endIndex)-1;
	}
	
	public List getPageList(){
		return getSource().subList(getFirstElementOnPage(), getLastElementOnPage()+1);
	}
}
